﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;

namespace WebNext.DataAccess.Infrastructure
{
	public class NHibernateEntityInterceptor : EmptyInterceptor
	{
		 public const string CreatedOn = "CreatedOn";
		  public const string CreatedBy = "CreatedBy";
		  public const string LastUpdatedOn = "LastUpdatedOn";
		  public const string LastUpdatedBy = "LastUpdatedBy";
 
		  private string _userName;

		  public NHibernateEntityInterceptor(string userName)
		  {
				this._userName = userName;
		  }
 
		  public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
		  {
				DateTime currentDate = DateTime.UtcNow;
				int indexOfCreatedOn = Array.IndexOf(propertyNames, CreatedOn);
				if(indexOfCreatedOn >= 0)
					 state[indexOfCreatedOn] = currentDate;
 
				int indexOfCreatedBy = Array.IndexOf(propertyNames, CreatedBy);
				if (indexOfCreatedBy >= 0)
					 state[indexOfCreatedBy] =this._userName;
 
				return true;
		  }
 
		  public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
		  {
				int indexOfUpdatedOn = Array.IndexOf(propertyNames, LastUpdatedOn);
				if (indexOfUpdatedOn >= 0)
					 currentState[indexOfUpdatedOn] = DateTime.UtcNow;
 
				int indexOfUpdatedBy = Array.IndexOf(propertyNames, LastUpdatedBy);
				if (indexOfUpdatedBy >= 0)
					 currentState[indexOfUpdatedBy] = this._userName;
 
				return true;
		  }
	}
}
